package common;

import common.commands.*;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.StringTokenizer;

import ui.WindowManager;
import ui.cli.console.Terminal;
import math.Relation;

public class Commands {

    private static HashMap<String, ICommand> commands = new HashMap<String, ICommand>();

    public static Collection<ICommand> getCommands() {

        return Collections.unmodifiableCollection(commands.values());
    }

    public static ICommand getCommand(String name) {
        if (commands.containsKey(name)) {
            return commands.get(name);
        } else {
            return null;
        }
    }

    public static void RegisterCommand(ICommand cmd) {
    	commands.put(cmd.getName().toUpperCase(), cmd);
    }
    
    public static void Prepare() {

        RegisterCommand(new CommandClose());
        RegisterCommand(new Print());
        RegisterCommand(new PrintModel());
        RegisterCommand(new LoadAltaRicaModel());
        RegisterCommand(new Reach());
        RegisterCommand(new CommandHelp());
        RegisterCommand(new CommandList());
        RegisterCommand(new CommandExit());
        RegisterCommand(new CommandGUI());
        RegisterCommand(new CommandSelectModel());
        RegisterCommand(new CommandCurrentModel());
        RegisterCommand(new CommandLoadWorkspace());
        RegisterCommand(new CommandSaveWorkspace());
        
    }

    public static CommandValue RunCommand(String input, boolean showCommand) {

        CommandValue ret = CommandValue.UNKNOWN;
        input = input.trim();
        StringTokenizer tok = new StringTokenizer(input);
        String cmd = "";
        if (tok.hasMoreTokens()) {
            cmd = tok.nextToken();
            String args = input.substring(cmd.length()).trim();

            ICommand command = commands.get(cmd.toUpperCase());
            if (WindowManager.getInstance().isVisible() && showCommand) {
            	ui.cli.console.Console.getInstance().sendOutput(input);
            }
            if (command != null) {
                ret = command.run(args);
                if (ret != CommandValue.OK) {
                    System.out.println("Error: the command " + cmd + " did not succeed");
                }
         
            }
            else {
                ret = Relation.parseRelation(input, new Relation());
            }
        }
        
        if (ret == CommandValue.UNKNOWN) {
        	System.out.println("Unknown command: " + cmd.trim());
        }
        System.out.print(Terminal.getPrompt());
        return ret;
    }
}
